package servlet;

import java.io.DataInputStream;
import java.io.IOException;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import ws.GestionFichiersInterfaceWS;
import ws.GestionFichiersInterfaceWSImplService;


/**
 * Servlet implementation class UploadServlet
 */
public class FileManagerServlet extends HttpServlet {
	
	//Appel au WebService//
	GestionFichiersInterfaceWSImplService service = new GestionFichiersInterfaceWSImplService();
	GestionFichiersInterfaceWS gestionFichiers = service.getGestionFichiersInterfaceWSImplPort();
		
	//private static String UPLOAD = "/upload.jsp"; //uploader des fichiers (id 1)
	private static String RELOAD = "/index.jsp";  //reloader la vue (id 2)
	private static String OPEN = "/open.jsp";     //ouvrir un fichier (id 3)
	private static String DOWNLOAD = "/download.jsp"; //télécharger un fichier sur son poste (id 4)
	private static String RENAME = "/rename.jsp"; //renommer un fichier (id 5)
	private static String REMOVE = "/remove.jsp"; //supprimer un fichier (id 6)
	private static String ERROR = "/error.jsp";   //cas d'erreur
	
	
	private static final long serialVersionUID = 1L;
    byte[] temp = null;
    /**
     * @see HttpServlet#HttpServlet()
     */
    public FileManagerServlet() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		
		//String idTache = request.getParameter("id");
		String idTache = "1";
		String forward = "";
		
		if (idTache.compareTo("1")==0){
		
			String saveFile="";
			String contentType = request.getContentType();
			if((contentType != null)&&(contentType.indexOf("multipart/form-data") >= 0)){
			DataInputStream in = new DataInputStream(request.getInputStream());
			int formDataLength = request.getContentLength();
			byte dataBytes[] = new byte[formDataLength];
			int byteRead = 0;
			int totalBytesRead = 0;
			while(totalBytesRead < formDataLength){
			byteRead = in.read(dataBytes, totalBytesRead,formDataLength);
			totalBytesRead += byteRead;
			}
			String file = new String(dataBytes);
			saveFile = file.substring(file.indexOf("filename=\"") + 10);
			saveFile = saveFile.substring(0, saveFile.indexOf("\n"));
			saveFile = saveFile.substring(saveFile.lastIndexOf("\\") + 1,saveFile.indexOf("\""));
			//int lastIndex = contentType.lastIndexOf("=");
			//String boundary = contentType.substring(lastIndex + 1,contentType.length());
			int pos;
			pos = file.indexOf("filename=\"");
			pos = file.indexOf("\n", pos) + 1;
			pos = file.indexOf("\n", pos) + 1;
			pos = file.indexOf("\n", pos) + 1;
		//	int boundaryLocation = file.indexOf(boundary, pos) - 4;
			//int startPos = ((file.substring(0, pos)).getBytes()).length;
			//int endPos = ((file.substring(0, boundaryLocation)).getBytes()).length;
			/*//File ff = new File(saveFile);
			FileOutputStream fileOut = new FileOutputStream(ff);
			fileOut.write(dataBytes, startPos, (endPos - startPos));
			fileOut.flush();
			fileOut.close();*/
			}
			
			// Récupération du flux entrant
			//java.io.DataInputStream dis = new java.io.DataInputStream(request.getInputStream());
			//dis.readFully(temp);
			//dis.close();
			//gestionFichiers.uploadAFile(saveFile);
			forward = RELOAD;
		}else{
			if (idTache.equals("2")){
				forward = RELOAD;
			}else{
				if (idTache.equals("3")){
					forward = OPEN;
				}else{
					if (idTache.equals("4")){
						forward = DOWNLOAD;
					}else{
						if (idTache.equals("5")){
							forward = RENAME;
						}else{
							if (idTache.equals("6")){
								forward = REMOVE;
							}else{
								forward = ERROR;
							}
						}
					}
				}
			}
		}
		RequestDispatcher view = request.getRequestDispatcher(forward);
		view.forward(request, response);
		
	}

}
